package library.model.service;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import library.dto.BookDTO;
import library.dto.Category_HighDTO;
import library.dto.MemberDTO;
import library.dto.ZipcodeDTO;
import library.model.dao.LibraryDAO;
import library.model.exception.DuplicatedIdException;
import library.model.exception.DuplicatedRegisterNumberException;

import org.springframework.web.multipart.MultipartFile;

public class LibraryService {
	
	private LibraryDAO dao;
	private String uploadDirectory; 
	public LibraryService(LibraryDAO dao, String uploadDirectory) {
		super();
		this.dao = dao;
		this.uploadDirectory = uploadDirectory;
	}
	//회원가입
	public void insertMember(MemberDTO mdto) throws SQLException,
																													 DuplicatedRegisterNumberException,
																													 DuplicatedIdException,
																													 IOException{
		if(dao.selectMemberById(mdto.getId()) !=null){
			throw new DuplicatedIdException(mdto.getId()+"는 이미 등록된 아이디입니다. ID를 변경하세요");
		}
		if((dao.selectMemberByRegisterNumber(mdto.getName(), mdto.getRegisterNumber1(), mdto.getRegisterNumber2())) != null){
			throw new DuplicatedRegisterNumberException("이미 가입된 주민등록번호입니다.");
		}
		MultipartFile file = mdto.getUpfile();
		if(!file.isEmpty()){	
			String filename = file.getOriginalFilename();
			String extension = filename.substring(filename.lastIndexOf("."));
			String newfilename =  System.currentTimeMillis()+extension;
			mdto.setPictureFilename(newfilename);
			file.transferTo(new File(uploadDirectory, newfilename));
		}
		mdto.setState_no(0);
		dao.insertMember(mdto);
	}
		

	// 중복된 ID 찾을떄, 회원정보 상세조회
	public MemberDTO selectMemberById(String id) throws SQLException {
		return dao.selectMemberById(id);
	}
	
	//주민번호로 Id찾기, 주민번호 중복 찾기
	public MemberDTO selectMemberByRegisterNumber(String name, String registerNo1, String registerNo2) throws SQLException{
		return dao.selectMemberByRegisterNumber(name, registerNo1, registerNo2);
	}
	//id와 주민번호로 비밀번호찾기
	public MemberDTO selectMemberByPassword(String id, String registerNo1, String registerNo2) throws SQLException{
		return dao.selectMemberByPassword(id, registerNo1, registerNo2);
	}
		
	//전체 회원 조회 -ken
	public ArrayList<MemberDTO> getAllMemberList() throws SQLException{
		return dao.selectAllMember();
	}
	// 사람이름으로 회원조회 -ken
		public ArrayList<MemberDTO> selectMemberByName(String name) throws SQLException {
				return dao.selectMemberByName(name);
		}
	//회원정보 수정
	public void updateMember(MemberDTO mdto, MemberDTO login_info) throws SQLException, IOException {
		System.out.println("11111111111111111");
		File oldFile = new File("C:\\apache-tomcat-6.0.35\\webapps\\library_system\\pictures\\"+login_info.getPictureFilename());
		oldFile.delete();
		MultipartFile file = mdto.getUpfile();
		if(!file.isEmpty()){	
			String filename = file.getOriginalFilename();
			String extension = filename.substring(filename.lastIndexOf("."));
			String newfilename =  System.currentTimeMillis()+extension;
			mdto.setPictureFilename(newfilename);
			file.transferTo(new File(uploadDirectory, newfilename));
			file.transferTo(new File("C:\\Users\\MasterKims\\Documents\\JAVA_Util\\workspace_ibatis\\library_system\\WebContent\\pictures", newfilename));
		}
		dao.updateMemberById(mdto);
	}
		//회원탈퇴
		public void removeMemberById(MemberDTO mto)throws Exception {
			dao.deleteMemberById(mto.getId());
//			업로드시 추가 - 파일 삭제
			new File(uploadDirectory, mto.getPictureFilename()).delete();
		}
	//우편번호찾기
	public ArrayList<ZipcodeDTO> selectByDong(String dong) throws SQLException{
		return dao.selectByDong(dong);
	}	
//	//대여현황
//	public ArrayList selectRentBreakDown(String id){
//		return dao.selectRentBreakDown(id);
//	}
//	//희망도서 신청
//	public void insertWishlist(String id,String bookName, String publisher, String writer) throws SQLException {
//		dao.insertWishlist(id, bookName, publisher, writer);
//	}
//	//희망도서 검색
//	public ArrayList selectWishList(String id)throws SQLException{
//		return dao.selectWishList(id);
//	}
//	//도서 대여,예약,취소
//	public void updateBookRent() throws SQLException{
//		
//	}	
//	//관심도서

	//대여한 책 이름으로 회원검색 - ken
	public ArrayList<MemberDTO> selectMemberByBook(String book) throws SQLException{
		return dao.selectMemberByBook(book);
	}
	//회원상태로 회원조회 - ken
	public ArrayList<MemberDTO> selectMemberByState(int state) throws SQLException{
		return dao.selectMemberByState(state);
	}
	//책 이름으로 책 검색
	public List searchBookByName(String name) throws SQLException{
		return  dao.selectBookByName(name);
	}	
	//회원정보상세 - 대여/예약/희망도서 리스트
	public HashMap getMemberBookList(String id) throws SQLException{
		return dao.selectMemberBookList(id);
	}

	//대분류 조회처리 - yong
	public ArrayList<Category_HighDTO> getAllHighCategory() throws SQLException{
		return dao.selectAllHighCategory();
	}
	
	//중분류 조회처리 - yong
	public ArrayList getAllMiddleCategory(String CategoryHighId) throws SQLException{
		return dao.selectAllMiddleCategory(CategoryHighId);
	}
	//SN로 책 조회 - ken
	public BookDTO searchBookBySN(String sn) {
		return dao.searchBookBySN(sn);
	}
	//저자로 책검색 -ken
	public List searchBookByWriter(String writer) {
		return dao.searchBookByWriter(writer);
	}
	//전체 책 조회 - ken
	public List searchBookAll() {
		return dao.searchBookAll();
	}

	//소분류 조회처리 - yong
	public ArrayList getAllLowCategory(String CategoryMiddleId) throws SQLException{
		return dao.selectAllLowCategory(CategoryMiddleId);
	}
	
	//책 리스트 불러오기(분류검색) - Yong
	public ArrayList getBookListByCategory(String CategoryLowId) throws SQLException{
		return dao.selectBookByCategory(CategoryLowId);
	}

	//상태로 도서 검색 - ken
	public List searchBookByState(int state) {
		return dao.searchBookByState(state);
	}

	//신착도서 결과 검색(7일 이내) - Yong
	public List searBookByInputDate(HashMap map) throws SQLException{
		return dao.selectBookByInputDate(map);
	}

	//인기 도서 검색 - Yong
	public List searchBookByCount(HashMap map) {
		return dao.selectBookByCount(map);
	}

}